package com.yet.container.loader;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.yet.container.registry.RegistryCenter;
import com.yet.container.registry.RegistryMeta.Address;
import com.yet.container.registry.RegistryMeta.ServiceMeta;
import com.yet.exception.RegistryNotFoundException;
import com.yet.rule.Rule;

/**
 * 实现服务的拉取 实现事件的监听：当本地发生注册或取消注册时，重新抓取
 */
public class ConsumerServiceLoader extends ServicesLoader {

	private static final Logger logger = LoggerFactory.getLogger(ConsumerServiceLoader.class);

	protected static final Map<ServiceMeta, List<Address>> holder = new ConcurrentHashMap<>();

	protected final RegistryCenter registryCenter;// 注册中心

	protected final Rule rule;

	public ConsumerServiceLoader(RegistryCenter registryCenter, Rule rule) {
		super();
		this.registryCenter = registryCenter;
		this.rule = rule;
	}

	@Override
	public void fetchSocketAddress() {
		synchronized (holder) {
			holder.putAll(registryCenter.load());
		}
	}

	@Override
	public void init() {
		fetchSocketAddress();// 启动时先将服务抓取到本地
		logger.debug("从[{}]抓取到服务:{}", getName(), holder);
		registryCenter.subscribe(null);// 监听根节点
	}

	@Override
	public void destroy() {
		holder.clear();
	}

	@Override
	public String getName() {
		return registryCenter.getName();
	}

	@Override
	public List<Address> lookupAddresses(ServiceMeta meta) {
		if (holder.get(meta) == null) {
			holder.put(meta, registryCenter.lookup(meta));
		}

		if (CollectionUtils.isEmpty(holder.get(meta))) {
			throw new RegistryNotFoundException("找不到服务:" + meta);
		}
		return holder.get(meta);
	}

	@Override
	public Rule getRule(String args) {
		return rule;
	}
}
